package de.teamgamma.cansat.groundstation.usb;

import java.util.Iterator;

import org.json.JSONObject;

import de.teamgamma.cansat.groundstation.transmitting.Transmitter;

/**
 * Class which coordinates the receiving process of incoming data
 * @author Alexander Ciupka
 */

public class Receiver {
	private JSONObject data;
	public static Receiver receiver;
	private Transmitter transmitter;
	
	/**
	 * gets the instance of this class
	 * @return the instance of this class
	 */
	
	public static Receiver getInstance() {
		if (receiver == null) {
			receiver = new Receiver();
			receiver.buildTransmitter();
		}
		return receiver;
	}
	
	/**
	 * gets the received JSON
	 * @return received JSON
	 */
	
	public JSONObject getData() {
		return data;
	}
	
	/**
	 * method to get all keys from the received JSON
	 * @return String array with all keys of the json
	 */
	
	public String[] getKeys(JSONObject data) {
		int counter = 0;
		//Iterator for the keys of the JSON
		Iterator<?> keys = data.keys();
		//String Array to save the keys
		String[] allKeys = new String[data.length()];
		while(keys.hasNext()) {
			//Save the actual key into the array
			allKeys[counter] = (String) keys.next();
			counter++;
		} 
		return allKeys;
	}
	
	/**
	 * private constructor
	 */
	
	private Receiver() {}
	
	/**
	 * Creates a new Transmitter Object
	 */
	
	private void buildTransmitter() {
		transmitter = new Transmitter();
	}
	
	/**
	 * @param data Received data
	 */
	
	public JSONObject convertData(JSONObject data) {
		JSONObject convertedData = new JSONObject();
		for(String currentKey : getKeys(data)) {
			try {
				convertedData.put(currentKey, Double.parseDouble(data.get(currentKey).toString()));
			} catch(Exception e) {
				convertedData.put(currentKey, data.get(currentKey));
			}
		}
		return convertedData;
		
	}
	
	public void receiveData(JSONObject data) {
		//create a JSON with the received data
		this.data = convertData(data);
		System.out.println(data.toString());
		transmitter.sendAll(this.data);
	}
}
